import { FunctionComponent, useState } from 'react';
import styles from './editHeader.module.scss';
import { Button, Typography, Space, Input, message } from 'antd';
import { EditOutlined, LeftOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router';
import useGetPageInfo from '../../../../hooks/useGetPageInfo';
import { useGetComponentInfo } from '../../../../hooks/useGetComponentInfo';
import { useRequest } from 'ahooks';
import { updateQuestion } from '../../../../api/question';
import { useKeyPress } from 'ahooks';
const EditHeader: FunctionComponent = () => {
  const { id } = useParams();
  const [isEdit, setIsEdit] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const nav = useNavigate();
  const { title, setPageInfo, css, description, js } = useGetPageInfo();
  const { components } = useGetComponentInfo();
  const { loading, runAsync } = useRequest(updateQuestion, { manual: true });
  const hanlderEdit = () => {
    setInputValue(title);
    setIsEdit(true);
  };
  const hanlderBlurAndEnter = () => {
    setPageInfo({ title: inputValue });
    setIsEdit(false);
  };
  const hanlderSave = async () => {
    if (loading) return;
    const saveObj = { title, css, description, js, components };
    await runAsync(id!, saveObj);
    message.success('保存成功!');
  };
  const hanlderPublish = async () => {
    if (loading) return;
    const saveObj = { title, css, description, js, components, isPublished: true };
    await runAsync(id!, saveObj);
    message.success('发布成功!');
    nav('/question/stat/' + id);
  };
  useKeyPress(['ctrl.s'], (e) => {
    e.preventDefault();
    hanlderSave();
  });
  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            {!isEdit && <Typography.Title>{title}</Typography.Title>}
            {isEdit && (
              <Input
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onBlur={hanlderBlurAndEnter}
                onPressEnter={hanlderBlurAndEnter}
              />
            )}
            {!isEdit && <EditOutlined onClick={hanlderEdit} />}
          </Space>
        </div>
        <div className={styles.main}></div>
        <div className={styles.right}>
          <Space>
            <Button onClick={hanlderSave} loading={loading}>
              保存
            </Button>
            <Button type="primary" onClick={hanlderPublish}>
              发布
            </Button>
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
